var map;
var markersArray = [];
var geocoder;
var infowindow = new google.maps.InfoWindow();
var currentPosition = 0;

function initializeMap() {
	geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(48.8528994, 2.3533165000000054);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("the-event-map"),myOptions);
    google.maps.event.addListener(map, 'click', function(event) {
    	placeMarker(event.latLng);
    });
}

function placeMarker(location) {
	  clearOverlays();
	  
	  
	  //Now the city
	  var latlng = new google.maps.LatLng(location.Pa, location.Qa);
	  geocoder.geocode({'latLng': latlng}, function(results, status) {
	      if (status == google.maps.GeocoderStatus.OK) {
			var marker = new google.maps.Marker({
			    position: latlng,
			    map: map
			});
			markersArray.push(marker);
	        if (results[1]) {
	          savePosition(location.Pa,location.Qa,results[1].address_components[1].long_name);
	          infowindow.setContent(results[1].formatted_address);
	          infowindow.open(map, marker);
	        } else {
	        	savePosition(location.Pa,location.Qa,"");
	        }
	      }
	    });
	  
	  map.setCenter(location);
}

function clearOverlays() {
	  if (markersArray) {
	    for (i in markersArray) {
	      markersArray[i].setMap(null);
	    }
	  }
}

$(function(){
	if ($("#step").val()==2) {
		initializeMap();
		$("#new-position").click(function(){
			if($(".eventName").val()!="") {
				saveCurrentPositionElements();
			}
		});
	}
	
});

function saveCurrentPositionElements() {
	var savePlace = $("#event-positions");
	copyElementPosition('eventLong',savePlace);
	copyElementPosition('eventLat',savePlace);
	copyElementPosition('eventTown',savePlace);
	copyElementPosition('eventName',savePlace);
	copyElementPosition('eventDescription',savePlace);
	currentPosition++;
	clearOverlays();
}

function copyElementPosition(element,dest){
	var currentElement = $("#"+element+currentPosition);
	if (element=="eventName") {
		dest.append("<br/>"+currentElement.val());
	var clone = currentElement.clone();
	if (clone.attr('type')!='hiddent') {
		clone.attr('type','hidden');
	}
	dest.append(clone);
	currentElement.val("");
	
	currentElement.attr('id',element+(currentPosition+1));
	currentElement.attr('name',element+'['+(currentPosition+1)+']');
	
	}
}

function savePosition(lat,long,town){
	$(".eventLong").val(long);
	$(".eventLat").val(lat);
	$(".eventTown").val(town);
}